<?php

namespace App\Component;

use App\Core\BaseListForm;
use App\Model\Merchants\MerchantsModel;
use App\Model\UserModel;
use EasySwoole\Http\Request;
use App\Util\UserIdentityHelper;

class LogListForm extends BaseListForm
{

    public $operator_id;
    public $record_id;
    public $operation_type;
    public $start_log_date;
    public $end_log_date;
    private $class = null;
    private $columns = [];
    const OPERATION_TYPE_CREATE = 1;
    const OPERATION_TYPE_DELETE = 3;
    const OPERATION_TYPE_UPDATE = 2;
    const STATE_FAILED = 0;
    const STATE_SUCCESS = 1;
    private $state_cn_arr = [
        self::STATE_FAILED => '失败',
        self::STATE_SUCCESS => '成功',
    ];
    private $operation_type_cn_arr = [
        self::OPERATION_TYPE_CREATE => '创建',
        self::OPERATION_TYPE_DELETE => '删除',
        self::OPERATION_TYPE_UPDATE => '修改',
    ];
    public function __construct($query, $class, $columns, Request $request)
    {
        $this->class = $class;
        $this->columns = $columns;
        parent::__construct($query, $request);
    }
    public function lists()
    {
        $pagination = $this->getPagination();
        $model = $this->class::makeQueryModel([], [], $pagination);
        if ($this->checkField($this->operator_id)) {
            $model->where(['operator_id' => $this->operator_id]);
        }
        if ($this->checkField($this->record_id)) {
            $model->where(['record_id' => $this->record_id]);
        }
        if ($this->checkField($this->operation_type)) {
            $model->where(['operation_type' => $this->operation_type]);
        }
        if ($this->checkField($this->start_log_date) && $this->checkField($this->end_log_date)) {
            $model->where(['log_date' => [[$this->start_log_date, $this->end_log_date], 'BETWEEN']]);
        }
        $model->order('log_date', 'DESC');
        $modelResult = $model->all();
        $list = [];
        $result = [
            'list'       => $list,
            'pagination' => $pagination
        ];
        if ($retArr = $modelResult->toArray()) {
            $merchantsIds = array_column($retArr, 'merchants_id');
            $operatorIds = array_column($retArr, 'operator_id');
            $merchantsArr = MerchantsModel::makeQueryModel(['id' => [$merchantsIds, 'in']])
                ->field('id, company_name')->all()->toArray();
            $operatorsArr = UserModel::makeQueryModel(['id' => [$operatorIds, 'in']])
                ->field('id, username')->all()->toArray();
            $merchantsMap = array_column($merchantsArr, null, 'id');
            $operatorsMap = array_column($operatorsArr, null, 'id');
            foreach ($modelResult as $v) {
                $item = $v->toArray();
                $beforeDataDesc = '【';
                $afterDataDesc = '【';
                $afterData = json_decode($item['after_data'], true);
                $beforeData = json_decode($item['before_data'], true);
                foreach ($afterData as $k => $val) {
                    if (isset($this->columns[$k])) {
                        $key = $k . '_cn_map';
                        $afterDataDesc .= $this->columns[$k]['name'] . '：' .
                            ($this->columns[$k]['default'] ?? (isset($this->columns[$k][$key]) ? $this->columns[$k][$key][$val] ?? $val : $val)) . '，';
                        $beforeData && $beforeDataDesc .= $this->columns[$k]['name'] . '：' . ($this->columns[$k]['default'] ?? $beforeData[$k]) . '，';
                    }
                }
                $beforeDataDesc = trim($beforeDataDesc, '，') . '】';
                $afterDataDesc = trim($afterDataDesc, '，') . '】';
                $item['operator_name'] = $operatorsMap[$item['operator_id']]['username'] ?? $item['operator_id'];
                $item['merchants_name'] = $merchantsMap[$item['merchants_id']]['company_name'] ?? $item['merchants_id'];
                $item['state_cn'] = $this->state_cn_arr[$item['state']] ?? $item['state'];
                $item['operation_type_cn'] = $this->operation_type_cn_arr[$item['operation_type']] ?? $item['operation_type'];
                $item['beforeDataDesc'] = $beforeDataDesc;
                $item['afterDataDesc'] = $afterDataDesc;
                unset(
                    $item['before_data'],
                    $item['after_data'],
                    $item['is_delete'],
                    $item['deleted_at'],
                    $item['state'],
                    $item['operation_type']
                );
                $list[] = $item;
            }
            $total = $model->lastQueryResult()->getTotalCount();
            $result['pagination']['total_count'] = $total;
            $result['list'] = $list;
        }
        return $this->success($result);
    }
}
